package cn.anecansaitin.whimsy.common.loot.predicate;

import cn.anecansaitin.whimsy.common.register.ModLootPredicates;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType;

import java.util.Optional;

public record LootPathCheck(Optional<String> path) implements LootItemCondition {
    public static final Codec<LootPathCheck> CODEC = RecordCodecBuilder.create(instance -> instance
            .group(ExtraCodecs.strictOptionalField(Codec.STRING, "path")
                    .forGetter(p -> p.path))
            .apply(instance, LootPathCheck::new));

    @Override
    public LootItemConditionType getType() {
        return ModLootPredicates.LOOT_PATH_CHECK.get();
    }

    @Override
    public boolean test(LootContext lootContext) {
        return path.isPresent() && new ResourceLocation(path.get()).equals(lootContext.getQueriedLootTableId());
    }

    public static Builder lootPath(ResourceLocation path) {
        return new Builder(path);
    }

    public static class Builder implements LootItemCondition.Builder {
        private Optional<String> path = Optional.empty();

        public Builder(ResourceLocation path) {
            setPath(path);
        }

        public Builder setPath(ResourceLocation path) {
            this.path = Optional.of(path.toString());
            return this;
        }

        @Override
        public LootItemCondition build() {
            return new LootPathCheck(path);
        }
    }
}
